<template>
    <n-flex justify="space-between" style="margin-bottom: calc(var(--gap) / 2)">
        <n-space>
            <n-popconfirm
                @positive-click="handlePositiveClick"
                v-if="checkedRowKeys && checkedRowKeys.length"
            >
                <template #trigger>
                    <n-button type="error" :loading="deleting">
                        <template #icon>
                            <n-icon size="16">
                                <AutoDeleteTwotone v-if="deleting" />
                                <DeleteSweepRound v-else />
                            </n-icon>
                        </template>
                        删除
                    </n-button>
                </template>
                你确定批量删除选中的数据吗？
            </n-popconfirm>
        </n-space>

        <n-space>
            <n-button type="primary" @click="emits('add')">
                <template #icon>
                    <n-icon>
                        <AddRound />
                    </n-icon>
                </template>
                添加
            </n-button>
        </n-space>
    </n-flex>
</template>

<script setup lang="ts">
import { AddRound, DeleteSweepRound, AutoDeleteTwotone } from '@vicons/material'
import { useMessage } from 'naive-ui'
import { PropType, ref } from 'vue'

const emits = defineEmits(['deleteDone', 'add'])

const props = defineProps({
    checkedRowKeys: {
        type: Array as PropType<(number | string)[]>
    },
    deleteService: {
        type: Function as PropType<
            (params: (string | number)[]) => Promise<unknown>
        >
    }
})

const message = useMessage()
const deleting = ref(false)
function handlePositiveClick() {
    if (!props.deleteService) {
        message.info('请配置 deleteService 参数')
        return
    }
    deleting.value = true
    props
        .deleteService(props.checkedRowKeys!)
        .then(() => {
            emits('deleteDone')
            message.success('删除成功')
        })
        .catch((e: Error) => {
            message.error(e.message)
        })
        .finally(() => (deleting.value = false))
}
</script>
